package com.itheima.security.distributed.uaa.service;

import com.alibaba.fastjson.JSON;
import com.itheima.security.distributed.uaa.dao.UserDao;
import com.itheima.security.distributed.uaa.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * SpringDataUserDetailsService
 * </p>
 *
 * @author flyduck
 * @since 2023/11/19
 */
@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDto userDto = userDao.getUserByUsername(username);
        if (userDto == null) {
            //用户查询不到，返回null，由Provider抛出异常
            return null;
        }

        //根据用户id查询用户的权限
        List<String> permissions = userDao.findPermissionsByUserId(userDto.getId());
        String[] permissionArray = permissions.toArray(new String[permissions.size()]);

        //将userDto转成json
        String principal = JSON.toJSONString(userDto);

        //这里暂时使用静态数据
        UserDetails userDetails = User.withUsername(principal)
                .password(userDto.getPassword())
                .authorities(permissionArray)
                .build();
        return userDetails;
    }
}
